package 每日一题;

import java.util.HashMap;
import java.util.HashSet;

public class 存在重复元素2 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num) && i-map.get(num)<=k)
                return true;
            map.put(num,i);
        }
        return false;
    }
    public boolean containsNearbyDuplicate1(int[] nums, int k){
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i>k)
                set.remove(nums[i-k-1]);
            if (set.contains(nums[i]))
                return true;
            set.add(nums[i]);
        }
        return false;
    }
}
